package com.dsz.apibackend.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dsz.apibackend.common.DeleteRequest;
import com.dsz.apibackend.common.ErrorCode;
import com.dsz.apibackend.common.IdRequest;
import com.dsz.apibackend.constants.UserConstant;
import com.dsz.apibackend.enums.InterfaceInfoStatusEnum;
import com.dsz.apibackend.exception.BusinessException;
import com.dsz.apibackend.mapper.InterfaceInfoMapper;
import com.dsz.apibackend.model.dto.interfaceInfo.InterfaceInfoAddRequest;
import com.dsz.apibackend.model.dto.interfaceInfo.InterfaceInfoInvokeRequest;
import com.dsz.apibackend.model.dto.interfaceInfo.InterfaceInfoQueryRequest;
import com.dsz.apibackend.model.dto.interfaceInfo.InterfaceInfoUpdateRequest;
import com.dsz.apibackend.model.vo.UserVO;
import com.dsz.apibackend.service.InterfaceInfoService;
import com.dsz.apibackend.service.UserService;
import com.dsz.apiclientsdk.client.MyClient;
import com.dsz.apiclientsdk.model.User;
import com.dsz.apicommon.model.domain.InterfaceInfo;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author dushangzhi
 * @description 针对表【interface_info(接口信息表)】的数据库操作Service实现
 * @createDate 2024-03-14 13:41:55
 */
@Service
public class InterfaceInfoServiceImpl extends ServiceImpl<InterfaceInfoMapper, InterfaceInfo>
        implements InterfaceInfoService {
    @Resource
    private MyClient myClient;
    @Resource
    private UserService userService;

    /**
     * 分页查询接口列表
     */
    @Override
    public Page<InterfaceInfo> pageInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Integer pageNum = interfaceInfoQueryRequest.getPageNum();
        Integer pageSize = interfaceInfoQueryRequest.getPageSize();
        if (pageNum <= 0 || pageSize <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<InterfaceInfo> interfaceInfoPage = new Page<>(pageNum, pageSize);
        return this.page(interfaceInfoPage);
    }

    /**
     * 添加接口
     */
    @Override
    public Long saveInterfaceInfo(InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        //1.校验参数
        if (interfaceInfoAddRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //校验接口名称
        String name = interfaceInfoAddRequest.getName();
        if (StringUtils.isBlank(name) || name.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口名称错误");
        }
        //校验接口描述
        String description = interfaceInfoAddRequest.getDescription();
        if (description != null && description.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口描述过长");
        }
        //校验接口地址
        String url = interfaceInfoAddRequest.getUrl();
        if (StringUtils.isBlank(url) || url.length() > 512) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口地址错误");
        }
        //校验接口请求头
        String requestHeader = interfaceInfoAddRequest.getRequestHeader();
        if (StringUtils.isBlank(requestHeader)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求头为空");
        }
        //校验接口响应头
        String responseHeader = interfaceInfoAddRequest.getResponseHeader();
        if (StringUtils.isBlank(responseHeader)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "响应头为空");
        }
        //校验请求类型
        String method = interfaceInfoAddRequest.getMethod();
        if (StringUtils.isBlank(method) || method.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求类型错误");
        }
        //校验请求参数
        String requestParams = interfaceInfoAddRequest.getRequestParams();
        if (StringUtils.isBlank(requestParams)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "缺少请求参数");
        }
        //2.判断是否为管理员
        boolean isAdmin = this.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //3.插入接口
        UserVO user = (UserVO) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        interfaceInfo.setUserId(user.getId());
        boolean save = this.save(interfaceInfo);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "插入失败");
        }
        return interfaceInfo.getId();
    }

    /**
     * 判断是否为管理员
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Object attribute = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        UserVO user = (UserVO) attribute;
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user.getUserRole() == 1;
    }

    /**
     * 修改接口信息
     */
    @Override
    public boolean updateInterfaceInfo(InterfaceInfoUpdateRequest interfaceInfoUpdateRequest, HttpServletRequest request) {
        //1.校验参数
        if (interfaceInfoUpdateRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //校验接口名称
        String name = interfaceInfoUpdateRequest.getName();
        if (StringUtils.isBlank(name) || name.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口名称错误");
        }
        //校验接口描述
        String description = interfaceInfoUpdateRequest.getDescription();
        if (description != null && description.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口描述过长");
        }
        //校验接口地址
        String url = interfaceInfoUpdateRequest.getUrl();
        if (StringUtils.isBlank(url) || url.length() > 512) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口地址错误");
        }
        //校验接口请求头
        String requestHeader = interfaceInfoUpdateRequest.getRequestHeader();
        if (StringUtils.isBlank(requestHeader)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求头为空");
        }
        //校验接口响应头
        String responseHeader = interfaceInfoUpdateRequest.getResponseHeader();
        if (StringUtils.isBlank(responseHeader)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "响应头为空");
        }
        //校验请求类型
        String method = interfaceInfoUpdateRequest.getMethod();
        if (StringUtils.isBlank(method) || method.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求类型错误");
        }
        //校验接口状态
        Integer status = interfaceInfoUpdateRequest.getStatus();
        if (status != null && (!status.equals(0) && !status.equals(1))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口状态错误");
        }
        //校验请求参数
        String requestParams = interfaceInfoUpdateRequest.getRequestParams();
        if (StringUtils.isBlank(requestParams)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "缺少请求参数");
        }
        //2.判断是否为管理员
        boolean isAdmin = this.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //3.更新数据库
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);
        boolean res = this.updateById(interfaceInfo);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return true;
    }

    /**
     * 删除接口
     */
    @Override
    public boolean deleteInterfaceInfo(DeleteRequest deleteRequest, HttpServletRequest request) {
        //1.校验参数
        if (deleteRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id应该大于0");
        }
        //2.判断是否为管理员
        boolean isAdmin = this.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //3.从数据库中删除
        boolean res = this.removeById(id);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return true;
    }

    /**
     * 发布接口
     */
    @Override
    public boolean onlineInterfaceInfo(IdRequest idRequest, HttpServletRequest request) {
        //1.校验参数
        if (idRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id<=0");
        }
        //2.判断是否为管理员
        boolean isAdmin = this.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //3.判断接口是否存在且可用
        InterfaceInfo interfaceInfo = this.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
        }
        // todo 判断接口是否可用的逻辑需要修改
        try {
            String s = myClient.testPost2(new User("dushangzhi"));
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口无法使用");
        }
        //4.修改接口状态
        if (interfaceInfo.getStatus().equals(InterfaceInfoStatusEnum.ONLINE.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已上线");
        }
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean res = this.updateById(interfaceInfo);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上线失败");
        }
        return true;
    }

    /**
     * 下线接口
     */
    @Override
    public boolean offlineInterfaceInfo(IdRequest idRequest, HttpServletRequest request) {
        //1.校验参数
        if (idRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = idRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id<=0");
        }
        //2.判断是否为管理员
        boolean isAdmin = this.isAdmin(request);
        if (!isAdmin) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //3.判断接口是否存在
        InterfaceInfo interfaceInfo = this.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
        }
        //4.修改接口状态
        if (interfaceInfo.getStatus().equals(InterfaceInfoStatusEnum.OFFLINE.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已下线");
        }
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean res = this.updateById(interfaceInfo);
        if (!res) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下线失败");
        }
        return true;
    }

    /**
     * 在线调用接口
     */
    @Override
    public Object invokeInterfaceInfo(InterfaceInfoInvokeRequest interfaceInfoInvokeRequest, HttpServletRequest request) {
        //1.校验参数
        if (interfaceInfoInvokeRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = interfaceInfoInvokeRequest.getId();
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id<=0");
        }
        String requestParams = interfaceInfoInvokeRequest.getRequestParams();
        if (StringUtils.isBlank(requestParams)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "缺少请求参数");
        }
        //2.判断接口是否存在
        InterfaceInfo interfaceInfo = this.getById(id);
        if (interfaceInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口不存在");
        }
        //3.检查接口是否已下线
        if (interfaceInfo.getStatus().equals(InterfaceInfoStatusEnum.OFFLINE.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口已下线");
        }
        // todo 在线调用接口的逻辑需要修改
        //4.在线调用接口
        UserVO currentUser = userService.getCurrentUser(request);
        com.dsz.apicommon.model.domain.User user = userService.getById(currentUser.getId());
        String accessKey = user.getAccessKey();
        String secretKey = user.getSecretKey();
        MyClient client = new MyClient(accessKey, secretKey);
        Gson gson = new Gson();
        User requestUser = gson.fromJson(requestParams, User.class);
        Object s;
        try {
            s = client.testPost2(requestUser);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口无法使用");
        }
        return s;
    }
}




